var zoqui;
if (typeof(zoqui) == "undefined") zoqui = {};

if (typeof(zoqui.Ajax) == "undefined")
	zoqui.Ajax = {}

zoqui.Ajax = function ()
{
	this.req = {};
}

zoqui.Ajax.prototype.makeRequest = function (url, onComplete)
{
    meth = "GET";	
	this.onComplete = onComplete;
	var pointer = this;	
	if (window.XMLHttpRequest){
		this.req = new XMLHttpRequest();
		this.req.onreadystatechange = function () { pointer.processReqChange() };
        //this.req.overrideMimeType('text/html; charset=utf-8');
		this.req.open("GET", url, true); //
		this.req.send(null);
	}
}

zoqui.Ajax.prototype.processReqChange = function()
{
	// only if req shows "loaded"
	if (this.req.readyState == 4) {
		if (this.req.status == 200){
			this.onComplete( {status:'OK',data: this.req} );
		} else {
            this.onComplete( {status:'ERROR',data: null} );
		}
	}
}

zoqui.Calendar = {

	OAuthCalendar: null,
	
	isLogged: function(){
		if (zoqui.Calendar.OAuthCalendar==null)
			return false;
		var ret =zoqui.Calendar.OAuthCalendar.hasToken(); 
		return ret;
	},
	
	initialize: function(){
		if (zoqui.Calendar.OAuthCalendar==null){
			zoqui.Calendar.OAuthCalendar=ChromeExOAuth.initBackgroundPage({
			    'request_url' : 'https://www.google.com/accounts/OAuthGetRequestToken',
			    'authorize_url' : 'https://www.google.com/accounts/OAuthAuthorizeToken',
			    'access_url' : 'https://www.google.com/accounts/OAuthGetAccessToken',
			    'consumer_key' : 'anonymous',
			    'consumer_secret' : 'anonymous',
			    'scope' : 'http://www.google.com/calendar/feeds/',
			    'app_name' : 'ConCal - Google Chrome Extension'
			});
		}
	},

	logout: function(){
		if (zoqui.Calendar.OAuthCalendar==null){
			return;
		}
		zoqui.Calendar.OAuthCalendar.clearTokens();
	},

	login: function(callback){
		if (zoqui.Calendar.OAuthCalendar==null)
			zoqui.Calendar.initialize();
		try{        
		    zoqui.Calendar.OAuthCalendar.authorize(function(){
		        if (callback)
		        	callback(true);
		    });
		}
		catch(err){
		    if (callback)
				callback(false);
		}
	},
	
	getEvent: function(url,callback){
		if (zoqui.Calendar.OAuthCalendar==null||(!zoqui.Calendar.isLogged()))
			return;
		zoqui.Calendar.OAuthCalendar.sendSignedRequest(
		    url, 
		    function(text,xhr){
		        try{
		            callback(eval('('+text+')'));
		            return;                
		        }
		        catch(err){
		            callback(null);
		            return;
		        }
		    },
		    {'parameters' : {'alt' : 'json'}}
		);    
	},

	extractLinkForRelation: function(entry,relation){
		var link = null;
		if (entry && entry.link && entry.link.length>0){				
			for(var i=0;i<entry.link.length;i++){
				if (entry.link[i].rel==relation){
					link=entry.link[i].href;
					break;
				}
			}				
		}
		return link;
	},	
	
	saveEvent : function(event,callback){
		if (zoqui.Calendar.OAuthCalendar==null||(!zoqui.Calendar.isLogged()))
			return;		
		var url = zoqui.Calendar.extractLinkForRelation(event,'edit');
		if (event.author)
			delete event.author;
		if (event['gd:who'])
			delete event['gd:who'];
		var body=Blz.XML.Parser.object2string(event,'entry',{"encoding":1,"href":1,"rel":1,"scheme":1,"src":1,"term":1,"type":1,"uri":1,"value":1,"valueString":1,"version":1,"xmlns":1,"xmlns:gCal":1,"xmlns:gd":1,"xmlns:openSearch":1,"endTime":1,"startTime":1});
		console.log('depois');
		console.log(body);
		body=body.replace(/\<entry/ig,"<entry xmlns='http://www.w3.org/2005/Atom' xmlns:gd='http://schemas.google.com/g/2005' xmlns:gCal='http://schemas.google.com/gCal/2005'");
		body=body.replace(/\@/g,"%40");
		var params = { 'method': 'PUT','body': body,'headers': { 'If-Match': '*', 'Content-Type':'application/atom+xml' } };
		zoqui.Calendar.OAuthCalendar.sendSignedRequest(
			url,
			function(text,xhr){
					try{
						//var obj = eval('('+text+')');
						var obj=Blz.XML.Parser.string2object(text);	 
						callback(obj);
						return;
					}
					catch(err){
						callback(null);
						return;
					}
			},
			params
		);	
	},
	
	getLastEvent : function(calendar,callback){
		if (zoqui.Calendar.OAuthCalendar==null||(!zoqui.Calendar.isLogged()))
			return;		
		var url = zoqui.Calendar.extractLinkForRelation(calendar,'http://schemas.google.com/gCal/2005#eventFeed');		
		zoqui.Calendar.OAuthCalendar.sendSignedRequest(
		    url, 
		    function(text,xhr){
		        try{
					var entry=null;
					console.log('antes');
					console.log(text);	        		
					var obj=Blz.XML.Parser.string2object(text);	 
					if (obj && obj.entry){
						var entries = obj.entry;
						if (entries.length>0){
							entry=entries[0];
						}
						else{
							entry=entries;
						}
					}
			        callback(entry); 
					return;	
		        }
		        catch(err){
	            callback(null);
	            return;
		        }
		    },
		    {'parameters' : {"orderby": "lastmodified", "max-results":"1" } }
		);
	},
	
	getCalendar: function(title,callback){
		if (zoqui.Calendar.OAuthCalendar==null||(!zoqui.Calendar.isLogged()))
			return;		
		zoqui.Calendar.OAuthCalendar.sendSignedRequest(
		    "https://www.google.com/calendar/feeds/default/owncalendars/full", 
		    function(text,xhr){
		        try{
					var entry=null;
					var obj=Blz.XML.Parser.string2object(text);	 	 
					if (obj && obj.entry){
						var entries = obj.entry;
						if (entries.length>0){
							for(var i=0;i<entries.length;i++){
								if (entries[i].title['#text']==title){
									entry=entries[i];
									break;
								}
							}
						}
						else{
							if (entries.title['#text']==title)
								entry=entries;
						}
					}
		            callback(entry);
		            return;              
		        }
		        catch(err){
		            callback(null);
		            return;
		        }
		    },
		    null
		);
	}
};
